package com.cclinux.projects.actcampus.service.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cclinux.framework.core.domain.PageParams;
import com.cclinux.framework.core.domain.PageResult;
import com.cclinux.framework.core.mapper.UpdateWhere;
import com.cclinux.framework.core.mapper.Where;
import com.cclinux.framework.helper.FileHelper;
import com.cclinux.framework.helper.FormHelper;
import com.cclinux.framework.helper.TimeHelper;
import com.cclinux.projects.actcampus.comm.OSSUtil;
import com.cclinux.projects.actcampus.comm.ProjectConfig;
import com.cclinux.projects.actcampus.mapper.UserMapper;
import com.cclinux.projects.actcampus.model.ActivityJoinModel;
import com.cclinux.projects.actcampus.model.NewsModel;
import com.cclinux.projects.actcampus.model.UserModel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.sql.ResultSetMetaData;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Notes: 用户管理业务逻辑
 * @Author: cclinux0730 (weixin)
 * @Date: 2024/12/15 12:10
 * @Ver: ccminicloud-framework 3.2.1
 */


@Service("ActCampusAdminUserService")
public class AdminUserService extends BaseMyAdminService {


    @Resource(name = "ActCampusUserMapper")
    private UserMapper userMapper;


    /**
     * 用户列表
     */
    public PageResult getAdminUserList(PageParams pageRequest) {

        Where<UserModel> where = new Where<>();

        // 关键字查询
        String search = pageRequest.getSearch();
        if (StrUtil.isNotEmpty(search)) {
            where.and(wrapper -> {
                wrapper.or().like("USER_NAME", search);
                wrapper.or().like("USER_ACCOUNT", search);
            });
        }

        // 条件查询
        String sortType = pageRequest.getSortType();
        String sortVal = pageRequest.getSortVal();
        if (StrUtil.isNotEmpty(sortType) && StrUtil.isNotEmpty(sortVal)) {
            switch (sortType) {
                case "status": {
                    where.eq("USER_STATUS", Convert.toInt(sortVal));
                    break;
                }
                case "sort": {
                    where.fmtOrderBySort(sortVal, "");
                    break;
                }
            }

        }

        // 排序
        where.orderByDesc("USER_ID");


        Page page = new Page(pageRequest.getPage(), pageRequest.getSize());
        return userMapper.getPageList(page, where, "*");
    }

    /**
     * 删除用户
     */
    public void delUser(long id) {
        userMapper.delete(id);
    }


    /**
     * 获取单个用户
     */
    public Map<String, Object> getUserDetail(long id) {
        return userMapper.getOneMap(id);
    }

    /**
     * 修改用户状态
     */
    public void statusUser(long id, int status) {
//        appError("{校园活动}该功能暂不开放，如有需要请加作者微信：cclinux0730");
        UpdateWhere<UserModel> uw = new UpdateWhere<>();
        uw.eq("USER_ID", id);
        uw.set("USER_STATUS", status);
        userMapper.edit(id, uw);
    }


    /**
     * 重置用户密码
     */
    public void editUserPwd(long id, String pwd) {

        UpdateWhere<UserModel> uw = new UpdateWhere<>();
        uw.eq("USER_ID", id);
        uw.set("USER_PASSWORD", DigestUtil.md5Hex(pwd));
        userMapper.edit(uw);
    }


    /**
     * 导出名单
     */
    public Map<String, Object> exportUserJoinExcel() {
//        appError("{校园活动}该功能暂不开放，如有需要请加作者微信：cclinux0730");
        Where<UserModel> whereUser = new Where<>();
        List<UserModel> list = userMapper.getAllList(whereUser, "*");


        try (
             Workbook workbook = new XSSFWorkbook()) {
            // 创建一个工作表
            Sheet sheet = workbook.createSheet("Data");
            // 获取结果集的元数据
            int columnCount = list.size();
            // 创建表头
            Row headerRow = sheet.createRow(0);
            Cell cell = headerRow.createCell(0);
            cell.setCellValue("用户id");
            Cell cell1 = headerRow.createCell(1);
            cell1.setCellValue("用户昵称");

            Cell cell2 = headerRow.createCell(2);
            cell2.setCellValue("账户昵称");

            Cell cell3 = headerRow.createCell(3);
            cell3.setCellValue("创建时间");

            Cell cell4 = headerRow.createCell(4);
            cell4.setCellValue("密码");

            // 填充数据
            int rowIndex = 1;

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < list.size(); i++) {
                Row row = sheet.createRow(rowIndex++);
                row.createCell(0).setCellValue(list.get(i).getUserId());
                row.createCell(1).setCellValue(list.get(i).getUserName());
                row.createCell(2).setCellValue(list.get(i).getUserAccount());

                Date date = new Date(list.get(i).getAddTime());
                row.createCell(3).setCellValue(dateFormat.format(date));
                row.createCell(4).setCellValue(list.get(i).getUserPwd());

            }

            // 调整列宽
            for (int i = 0; i < columnCount; i++) {
                sheet.autoSizeColumn(i);
            }
            // 保存 Excel 文件
            try (FileOutputStream fileOut = new FileOutputStream("output.xlsx")) {
                workbook.write(fileOut);
                System.out.println("Excel 文件生成成功！");

                MultipartFile multipartFile = convert(workbook, "file", "output.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                OSSUtil ossUtil = new OSSUtil();
                String result = ossUtil.putDynamicObject(multipartFile);
                System.out.println(result);;

                Map<String, Object> map = new HashMap<>();
                map.put("url", result);
                map.put("total", list.size());

                return map;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static MultipartFile convert(Workbook workbook, String name, String originalFilename, String contentType) throws Exception {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            workbook.write(bos);
            byte[] bytes = bos.toByteArray();
            return new MockMultipartFile(name, originalFilename, contentType, bytes);
        }
    }

}
